"""
The web based application offers mathematical equations(additions and substractions)
in the form like
3+?=15 or ?-12=3
The user, usually kids, have to calculate the equation and submit the result.
If the result is correct, happy smileys are shown, otherwise sad smileys are shown.
The difficulty level of the equations can be set.

the project is written in python for the apache mod_python module.

Copyright by Alex Greif, 2006
"""




from mod_python import apache, Session, util

from random import Random

_SCRIPT_URL = '/scripts/mathePlusMinus'


def index(req):
    req.content_type = 'text/html'
    session = Session.Session(req)
    session['errors'] = 0
    if not 'maximum' in session:
        session['maximum'] = 4
    session['exerciseCount'] = 0
    
    newGuess(session)
    equation = session['equation']
    solution = session['solution']
    exerciseCount = session['exerciseCount']
    
    return getHtml(equation=equation, solution=solution,
                        exerciseCount=exerciseCount,
                        message='&nbsp;',
                        messageColor='black',
                        errors=session['errors'],
                        maximum=session['maximum'],
                        smiley = HAPPY_SMILEYS[0])

def guess(req, guess, maximum):
    session = Session.Session(req)
    if session.is_new():
        util.redirect(req, _SCRIPT_URL)
    try:
        session['maximum'] = int(maximum)
    except:
        pass
        
    solution = session['solution']
    if guess == str(solution):
        newGuess(session)
        message = 'Prima!'
        messageColor = '00FF00',
        smiley = HAPPY_SMILEYS[Random().randint(0, len(HAPPY_SMILEYS)-1)]
    else:
        if guess != '':
            session['errors'] += 1
        message = 'nochmal'
        messageColor = 'red'
        smiley = SAID_SMILEYS[Random().randint(0, len(SAID_SMILEYS)-1)]
    session.save()
    equation = session['equation']
    solution = session['solution']
    exerciseCount = session['exerciseCount']
    
    return getHtml(equation=equation, solution=solution,
                        exerciseCount=exerciseCount,
                        message=message,
                        messageColor=messageColor,
                        errors=session['errors'],
                        maximum=session['maximum'],
                        smiley=smiley)


def newGuess(session):
    equation, solution = _getEquation(maximum=session['maximum'])
    try:
        session['exerciseCount'] += 1
    except:
        session['exerciseCount'] = 1
    session['equation'] = equation
    session['solution'] = solution
    session.save()


def getHtml(**kwargs):
    kwargs['smileys'] = ('<img src="%s"> ' % kwargs['smiley']) * \
        (kwargs['exerciseCount']-kwargs['errors'])
    #kwargs['smileys'] = ''
        
    kwargs['scriptUrl'] = _SCRIPT_URL

    return '''
    <html>
     <head>
     <script language="JavaScript">
        <!--
          function setFocus() {
            document.form1.guess.focus();
          }
        //-->
     </script>
     <body onLoad="setFocus()">
      <form action="%(scriptUrl)s/guess" name="form1" method="POST">
      <h1>
       Mathe Plus/Minus-&Uuml;bungen (bis
       <input type="text" name="maximum" value="%(maximum)s"size="2">)
      </h1>
      <br>
      <h2>
       <font color="%(messageColor)s">%(message)s</font>
       &nbsp;&nbsp;&nbsp;&nbsp;
       %(smileys)s
      </h2>
      <h2>Deine %(exerciseCount)s. Aufgabe:</h2>
      <br>
      <br>
      <strong><font color="blue" face="Courier New" size="+4">%(equation)s</font></strong>
      <br>
      <br>
      <br>
       <input type="text" name="guess" width="10">
       <input type="submit" value="Los!">
      </form
      <br>
      <h2>Fehler: %(errors)s</h2>
      <br>
      <br>
      <br>
      <a href="/scripts/mathePlusMinus">neu starten</a>
     </body>
    </html>
    ''' % kwargs




def _getEquation(maximum):
    """
    Returns the tuple with equation and solution.
    """
    while True:
        a = Random().randint(0,maximum)
        b = Random().randint(0,maximum)
        plus = True
        if maximum > 10:
            plus = Random().randint(0,1)
        position = Random().randint(0,2)
        if plus:
            if a+b <= maximum:
                l = [a,b,a+b]
                solution = l[position]
                l[position] = '?'
                return ('%s + %s = %s' % tuple(l), solution)
        else:
            if maximum > a-b >= 0:
                l = [a,b,a-b]
                solution = l[position]
                l[position] = '?'
                return ('%s - %s = %s' % tuple(l), solution)



SAID_SMILEYS = [
    "http://www.my-smileys.de/smileys2/denknach.gif",
    "http://www.my-smileys.de/smileys2/crash_2.gif"
    
]


HAPPY_SMILEYS = [
    "http://www.my-smileys.de/smileys2/04b.gif",
    "http://www.my-smileys.de/smileys2/00009098.gif"

]















